package cn.qayy.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;

import cn.qayy.constants.CollectionConstant;
import cn.qayy.constants.Constant;
import cn.qayy.dto.FocusOnDTO;
import cn.qayy.dto.FocusOnDTO;
import cn.qayy.dto.Msg;
import cn.qayy.dto.MsgInfo;
import cn.qayy.po.Basis;
import cn.qayy.po.Bid;
import cn.qayy.po.KdbNssFocuson;
import cn.qayy.service.IFocusOnService;
import cn.qayy.service.SynchronizationService;
import cn.qayy.service.Uploadable;
import cn.qayy.utils.DownLoadUtil;
import cn.qayy.utils.ExcelUtils;
import cn.qayy.utils.JsonUtil;
import cn.qayy.utils.ResonseUtils;
import cn.qayy.utils.ServletContextUtils;
import cn.qayy.utils.StringUtil;
import cn.qayy.utils.UploadHandler;

/**
 * @author wangyu
 */
@Controller
@RequestMapping(value = "/focus/")
@SuppressWarnings("all")
public class FocusOnController {
	// 注入service
	@Resource(name = "focusOnServiceImpl")
	private IFocusOnService focusService = null;
	
	@Resource(name = "synchronizationImpl")
	private SynchronizationService synchronizationService = null;
	
	List<String> multiselectCondi = new ArrayList<String>(); // 可多选的条件

	Logger log = Logger.getLogger(FocusOnController.class);
    
	/***
     * 重复项判断时使用，新增了KdbNssFocuson或更新了KdbNssFocuson,同步更新到Context缓存里的数据
     * @param list
     */
    private void addToContext(List<KdbNssFocuson> list) {
    	/***
    	 * 获取项目上下文的共享数据
    	 */
    	ServletContext servletContext = ServletContextUtils.getServletContext();
    	//Qs名keys
    	Set<String> qsKeys = (Set<String>)servletContext.getAttribute("focusKeys");
		for (KdbNssFocuson b : list) {
			qsKeys.add(StringUtil.concat(b.getQs(), b.getId() + ""));
		}
    }
    /***
     * 重复项判断时使用，新增了KdbNssFocuson或更新了KdbNssFocuson,同步更新到Context缓存里的数据
     * @param list
     */
    private void removeToContext(List<KdbNssFocuson> list) {
    	/***
    	 * 获取项目上下文的共享数据
    	 */
    	ServletContext servletContext = ServletContextUtils.getServletContext();
    	//Qs名keys
    	Set<String> qsKeys = (Set<String>)servletContext.getAttribute("focusKeys");
    	for (KdbNssFocuson b : list) {
    		qsKeys.remove(StringUtil.concat(b.getQs(), b.getId() + ""));
    	}
    }
    
	/***
	 * 重点终端页面下载已筛选的记录
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "focus_download")
	public void focus_download(HttpServletRequest request, HttpServletResponse response) {
		try {
			List<FocusOnDTO> loadDataList = DownLoadUtil.getInstance().getTargetDownLoadDataList(FocusOnDTO.class);
			String downloadPath = ExcelUtils.getInstance().dataToExcelDxls("重点终端",StringUtil.listToStrArray(CollectionConstant.focus_mb),loadDataList);
			String url = request.getContextPath()+"/servlet/FileDownServlet?url="+downloadPath;
			response.sendRedirect(url);
		} catch (Exception e) {
			e.printStackTrace();
		}  
	}
	
	//Excel批量上传
	@ResponseBody
	@RequestMapping(value = "upload")
	public String uploadGFList(@RequestParam("excelFile") MultipartFile file,HttpServletRequest request) {
		String resultList ="";
    	Msg msg = null;
    	int listSize = 0;	//excel记录数
    	int doSize = 0;	//执行成功记录数
    	boolean isSucessful = false;
		try {
			Map<String, List<Uploadable>> map = UploadHandler.getLastData(file,FocusOnDTO.class);
			/**用户上传的总记录数**/
			MsgInfo msgInfo = (MsgInfo)map.get("totalCount").get(0);
			listSize = StringUtil.parseInt(msgInfo.getErr_num());
			
			if(map.get("fail") != null && !map.get("fail").isEmpty()) {
				List<Uploadable> list = map.get("fail");
				msg = new Msg(Constant.CHECK_CODE,list);
				resultList = JSONObject.toJSONString(msg);
			} else {//DB持久化
				List<Uploadable> listE = map.get("E");
				if(listE!=null && !listE.isEmpty()) {
					/**待更新的实体list**/
					List<KdbNssFocuson> list = new ArrayList<KdbNssFocuson>(listE.size()+1);
					List<KdbNssFocuson> old_list = new ArrayList<KdbNssFocuson>(listE.size()+1);
					for (Uploadable u : listE) {
						FocusOnDTO dto = (FocusOnDTO)u;
						//封装数据
						KdbNssFocuson focus = focusService.selectFocusByID(StringUtil.parseInt(dto.getId()));
						old_list.add(focus);
						if(focus != null) {
							focus.setByDTO(dto);
							list.add(focus);
						}
					}
					if(list != null && list.size()>0) {
						doSize = doSize +focusService.updateByList(list);
						removeToContext(old_list);
						addToContext(list);
						isSucessful = true;
					}
				}
				
				List<Uploadable> listN = map.get("N");
				if(listN!=null && !listN.isEmpty()) {
					//待新增的实体list
					List<KdbNssFocuson> list = new ArrayList<KdbNssFocuson>(listN.size()+1);
					for (Uploadable u : listN) {
						FocusOnDTO dto = (FocusOnDTO)u;
						//封装数据
						KdbNssFocuson focus = new KdbNssFocuson();
						focus.setByDTO(dto);
				        list.add(focus);
					}
					if(list != null && list.size()>0) {
						doSize = doSize +focusService.insertByList(list);
						addToContext(list);
						isSucessful= true;
					}
				}
				if(isSucessful) {
					log.info("总记录数："+listSize);
					log.info("总受影响行数："+doSize);
					// 同步更新流向
					// 正常操作前台提示消息 
					msg = new Msg(Constant.SUCESSFUL_CODE,"总记录数："+listSize+"，总成功数："+listSize+"，请核查！");
					resultList = JSONObject.toJSONString(msg);
				} else {
					throw new Exception();
				}
			}
		} catch (Exception e) {
			//异常后的前台提示消息
			e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE,Constant.FAIL_MSG+e.getMessage());
			resultList = JsonUtil.object2json(msg);
		}
		return resultList;
	}

	@ResponseBody
	@RequestMapping(value = "selectFoucsList")
	public String selectFoucsList(@RequestParam Map<String, Object> condiMap) {
		//对map进行过滤，除去空格
		condiMap = StringUtil.trim4Map(condiMap);
		String resultList = "";
		try {
			multiselectCondi.add("id");
	        for(String obj: condiMap.keySet()){
	            if(multiselectCondi.contains(obj)){
	            	if(condiMap.get(obj)!=null){
	                	if(obj.equals("id")) {
	                		String[] array = StringUtil.strToArray((String) condiMap.get(obj)," ");
	                		if (array!=null) {
	    						condiMap.put(obj.toString(), array);
	    					} else {
	    						condiMap.put(obj.toString(), null);
	    					}
	                	}else {
	                		String[] array = StringUtil.strToArray((String) condiMap.get(obj),",");
	                		if (array!=null) {
	    						condiMap.put(obj.toString(), array);
	    					} else {
	    						condiMap.put(obj.toString(), null);
	    					}
	                	}
					}
				} else if (condiMap.get(obj).equals("")) {
					condiMap.put(obj.toString(), null);
				}

			}
			PageInfo<Map<String, Object>> listMap = focusService.selectFocusBy(condiMap);
			resultList = JSONObject.toJSONString(listMap);
		} catch(Exception e) {
			//异常后的前台提示消息
			e.printStackTrace();
			Msg msg = new Msg(Constant.FAIL_CODE,e.getMessage());
			resultList = JsonUtil.object2json(msg);
		}
		return resultList;
	}

	@ResponseBody
	@RequestMapping(value = "selectFoucsByID")
	public Object selectFoucsByID(@RequestParam Integer focusId) {
		try {
			KdbNssFocuson focus = focusService.selectFocusByID(focusId);
			Object obj = JSONObject.toJSON(focus);
			return obj;
		} catch (Exception e) {
			e.printStackTrace();
			Msg msg = new Msg(Constant.FAIL_CODE,Constant.FAIL_MSG+e.getMessage());
			return JsonUtil.object2json(msg);
		}
	} 
	
	/***
	 * 页面新增、修改好伙伴
	 * @param dto
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "changeFocusOn")
	public Object changeFocusOn(FocusOnDTO dto,HttpServletRequest request) {
		//返回结果
		String result = "";
		String flag = (String) request.getParameter("flag");		
		Msg msg = null;
		if(flag.equals("N")) {	//N:新增
			dto.setIsUpdate("N");
		}else if(flag.equals("E")){//E:修改
			dto.setIsUpdate("E");
		}
		try {
			//验证数据
			Map<String, List<Uploadable>> map = UploadHandler.getLastData(dto);
			if(map.get("fail") != null && !map.get("fail").isEmpty()) {
				/**
				 * 验证不通过，前台提示消息 
				 */
				List<Uploadable> list = map.get("fail");
				msg = new Msg(Constant.CHECK_CODE,list);
				result = JSONObject.toJSONString(msg);
			} else {//验证通过，DB持久化
				List<Uploadable> listE = map.get(flag);
				if(listE!=null && !listE.isEmpty()) {
					List<KdbNssFocuson> list = new ArrayList<KdbNssFocuson>(listE.size()+1);
					List<KdbNssFocuson> old_list = new ArrayList<KdbNssFocuson>(listE.size()+1);
					for (Uploadable u : listE) {
						dto = (FocusOnDTO)u;
						//封装数据
						KdbNssFocuson focusOn = new KdbNssFocuson();
						if(flag.equals("E")) {
							focusOn = focusService.selectFocusByID(StringUtil.parseInt(dto.getId()));
							old_list.add(focusOn);
						}
						focusOn.setByDTO(dto);
				        list.add(focusOn);
					}
					if(flag.equals("N")) {	//N:新增
						focusService.insertByList(list);
						addToContext(list);
					}else if(flag.equals("E")){//E:修改
						focusService.updateByList(list);
						removeToContext(old_list);
						addToContext(list);
					}
				}
				/**
				 * 正常操作前台提示消息
				 */
				msg = new Msg(Constant.SUCESSFUL_CODE,Constant.SUCESSFUL_MSG);
				result = JsonUtil.object2json(msg);
			}
		} catch (Exception e) {
			/**
			 * 异常后的前台提示消息
			 */
			e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE,Constant.FAIL_MSG+e.getMessage());
			result = JsonUtil.object2json(msg);
		}
		return JSONObject.toJSON(result);
	}
	
	/***
	 * 获取待复制的id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "selectIds")
	public Object selectIds(HttpServletResponse response,HttpServletRequest request) {
		JSONObject json = new JSONObject();
		StringBuilder result=new StringBuilder();
		Msg msg = null;
		try {
			//获取缓存中的筛选条件
			Map<String, Object> params = (Map<String, Object>)DownLoadUtil.get("FocusOnDTO");
			if(params == null) {
				params = new HashMap<String, Object>();
				params.put("t", "1127");
			}
			List<Integer> list = focusService.selectIdsByMap(params);
			if(list != null && list.size()>0) {
				for (Integer id : list) {
					result.append(id+" ");
				}
				result.deleteCharAt(result.toString().length()-1);
			}
		} catch(Exception e) {
			e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE, Constant.FAIL_MSG+e.getMessage());
			return msg;
		}
		json.put("ids", result.toString());
		ResonseUtils.writeResponseByJson(response, json);
		//封装成json返回给前台
		return null;
	}
}
